package client

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"onerk4/zg5yk/ordering/common/proto/order"
)

type OrderHandler func(ctx context.Context, in order.OrderClient) (interface{}, error)

func OrderClient(ctx context.Context, handler OrderHandler) (interface{}, error) {
	// 1.连接
	conn, err := grpc.Dial("127.0.0.1:8081", grpc.WithInsecure())
	if err != nil {
		fmt.Printf("连接异常： %s\n", err)
		return nil, err
	}
	defer conn.Close()
	c := order.NewOrderClient(conn)
	res, err := handler(ctx, c)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func CreateOrder(ctx context.Context, req *order.CreateOrderRequest) (*order.CreateOrderResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, in order.OrderClient) (interface{}, error) {
		login, err := in.CreateOrder(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.CreateOrderResponse), nil
}

func Callback(ctx context.Context, req *order.CallbackRequest) (*order.CallbackResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, in order.OrderClient) (interface{}, error) {
		login, err := in.Callback(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.CallbackResponse), nil
}

func ShowOrderList(ctx context.Context, req *order.ShowOrderListRequest) (*order.ShowOrderListResponse, error) {
	client, err := OrderClient(ctx, func(ctx context.Context, in order.OrderClient) (interface{}, error) {
		login, err := in.ShowOrderList(ctx, req)
		if err != nil {
			return nil, err
		}
		return login, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*order.ShowOrderListResponse), nil
}
